﻿using System;
using Kiva7.DataClasses;
using System.ComponentModel;
using Kiva7.Utilities;
using Kiva7.ViewModels;

namespace Kiva7.DataRequests
{
    public class PartnerRequest : BaseViewModel
    {

        private Partner _partner;
        private static string PartnerConst = Name.Of<PartnerRequest>(x => x.Partner);
        public Partner Partner
        {
            get
            {
                return _partner;
            }
            set
            {
                if (_partner != value)
                {
                    _partner = value;
                    NotifyPropertyChanged(PartnerConst);
                }
            }
        }

        private bool _isloaded;
        private static string IsLoadedConst = Name.Of<PartnerRequest>(x => x.IsLoaded);
        public bool IsLoaded
        {
            get
            {
                return _isloaded;
            }
            set
            {
                if (_isloaded != value)
                {
                    _isloaded = value;
                    NotifyPropertyChanged(IsLoadedConst);
                }
            }
        }

        PartnersRequest _partnersRequest;
        internal void GetPartner(int partnerId)
        {
            if (_partnersRequest == null)
            {
                _partnersRequest = new PartnersRequest();
                _partnersRequest.OnResponse += partnersRequest_OnResponse;
            }
            IsLoaded = false;
            if (_partnersRequest.IsLoaded)
            {
                if (_partnersRequest.Partners.ContainsKey(partnerId))
                {
                    Partner = _partnersRequest.Partners[partnerId];
                }
                else
                {
                    Partner = null;
                }
                IsLoaded = true;
            }
            else
            {
                _partnersRequest.GetPartner(partnerId);
            }
        }

        void partnersRequest_OnResponse(object sender, DataRequest<DataResponse.PartnersResponse, Partner>.DataRequestEventArgs e)
        {
            if (!e.Cancelled
                && e.Exception == null)
            {
                int partnerId = (int)e.UserState;
                if (_partnersRequest.Partners.ContainsKey(partnerId))
                {
                    Partner = _partnersRequest.Partners[partnerId];
                }
                else
                {
                    Partner = null;
                }
                IsLoaded = true;
            }
            else if (e.Exception != null)
            {
                ExceptionHandler.HandleException(e.Exception);
            }
        }

        public void Clear()
        {
            Partner = null;
        }
    }
}
